<template>
  <div class="upload-list">
    <div class="demo-upload-list" :style="`width: ${size}px ; height: ${size}px`" v-for="(item,index) in uploadList">
      <template class="flex">
        <img :src="item.path"/>
        <div class="demo-upload-list-cover" v-if="item.status == 'success'">
          <Icon type="ios-eye-outline" @click.native="handleView(item.path)"></Icon>
          <Icon type="ios-trash-outline" @click.native="handleRemove(item,index)"></Icon>
        </div>
        <cusProgress ref="cusProgress" :status="item.status" width="90px"></cusProgress>
      </template>
    </div>

    <cus-upload  v-if="uploadList.length < maxCount" :maxSize="maxSize" :accept="accept"
                @onBeforeUpload="onBeforeUpload">
      <div :style="`width: ${size}px ; height: ${size}px`" class="upload-img">
        <Icon type="ios-add" size="30"/>
        <div class="upload-img-label">上传图片</div>
      </div>
    </cus-upload>
  </div>
</template>

<script>
  /**
   * @value [{path: '图片路径', status: '图片状态'}]  loading: 上传中, success: 上传成功, wrong: 上传失败
   * @keyLabel      上传文件字段
   * @params        上传文件额外属性
   * @fnc           上传文件方法
   * @deleteFnc     图片删除方法
   * @syncDelete    是否同步删除图片
   * @maxCount      最大可上传数量
   *
   * @onClear 清除暂缓区图片
   */
  import { uploadIMG, deleteIMG } from '@/api/organ/business'
// import { number } from 'echarts'

  export default {
    name: 'cus-uploadIMG',
    data () {
      return {
        uploadList: [],
        deleteList: [],

        option: {
          img: '',
          size: 1024,
          outputType: 'png'
        },
        imgTypeArr: ["image/png", "image/jpg", "image/jpeg"],//上传图片类型限制
      }
    },
    props: {
      size: {
          type: Number,
          default: 104
      },
      value: {
        type: Array,
        default: () => {
          return []
        }
      },
      keyLabel: {
        type: String,
        default: 'file'
      },
      maxSize: {
        type: Number,
        default: 2048
      },
      accept: {
        type: String,
        default: 'image/*'
      },
      params: {
        type: Object,
        default: () => {
          return {}
        }
      },
      syncDelete: {
        type: Boolean,
        default: true
      },
      fnc: {
        type: Function,
        default: uploadIMG
      },
      deleteFnc: {
        type: Function,
        default: deleteIMG
      },
      maxCount: {
        type: [String, Number],
        default: 1
      },
      returnLabel: {
        type: String,
        default: 'data'
      }
    },
    watch: {
      value (newV) {
        this.uploadList = newV
      }
    },
    methods: {
      handleView (path) {
        this.$cu.previewImage(path)
      },
      handleRemove (item, index) {
        if (item.status === 'loading') return this.$Message.wrong('当前图片正在上传中,不可删除')
        this.$cu.dialog({ content: '确认删除改图片?' }).then(() => {
          if (this.syncDelete) {
            this.deleteFncApi(item, index)
          } else {
            // 记录当前被删除数据
            this.deleteList.push(item)
            this.uploadList.splice(index, 1)
          }
        })
      },
      // 清除暂缓区图片
      onClear () {
        return new Promise((resolve) => {
          let promise = []
          for (let i = 0; i < this.deleteList.length; i++) {
            promise.push(this.deleteFncApi(this.deleteList[i], null))
          }
          Promise.all(promise).then(() => {
            this.deleteList = []
            resolve()
          })
        })
      },
      onBeforeUpload (file) {
        
         //上传文件之前钩子函数
      let that = this
      // 控制文件上传格式
      var imgType = this.imgTypeArr.indexOf(file.type) !== -1
      if (!imgType) {
        this.$Message.warning({
          content: '文件  ' + file.name + '  格式不正确, 请选择jpg或png或jpeg.',
          duration: 5
        });
        return false
      }
      let upload = { path: '', status: 'active' }
			this.uploadList.showProgress = true
			upload.path = window.URL.createObjectURL(file)
			this.option.img = upload.path
			this.uploadList.push(upload)
        // return;
        that.upload(file, upload)
      },
      // 图片上传接口
      upload (file, upload) {
        let params = new FormData()
        params.append(this.keyLabel, file)

        for (const key in this.params) {
          params.append(key, this.params[key])
        }

        this.fnc(params).then(res => {
       
          if (res.code === 1 || res.retCode == 2000) {
            upload.status = 'success'
            upload.path = res[this.returnLabel]
            this.$Message.success('文件上传成功')
          } else {
            upload.status = 'wrong'
          }
          this.uploadList = this.uploadList.filter(v => v.status === 'success')
          this.$emit('update:value', this.uploadList)
        }).catch(() => {
          upload.status = 'wrong'
          this.uploadList = this.uploadList.filter(v => v.status === 'success')
          this.$emit('update:value', this.uploadList)
        })
      },
      // 图片上传接口
      deleteFncApi (item, index) {
        return new Promise((resolve, reject) => {
          this.deleteFnc({ url: item.path }).then((res) => {
            if (res.code === 1) {
              resolve()
              if (index === 0 || index) {
                this.$Message.success('文件删除成功')
                this.uploadList.splice(index, 1)
              }
            } else {
              reject()
            }
          })
        })
      }
    }
  }
</script>

<style scoped lang="less">
  .upload-list {
    display: flex;
    align-items: center;
    /*padding-bottom: 25px;*/
  }

  .demo-upload-list {
    width: 104px;
    height: 104px;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
    margin-right: 4px;
  }

  .demo-upload-list img {
    width: 100%;
    height: 100%;
  }

  .demo-upload-list-cover {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    display: none;
    justify-content: center;
    align-items: center;
    background: rgba(0, 0, 0, .6);
  }

  .demo-upload-list:hover .demo-upload-list-cover {
    display: flex;
  }

  .demo-upload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }

  .upload-img {
    border: 1px dashed #dcdee2;
    border-radius: 4px;
    text-align: center;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color .2s ease;
    width: 104px;
    height: 104px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    background: rgba(0, 0, 0, 0.04);

    &-label {
      margin-top: 10px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.65);
      line-height: 22px;
    }
  }

  .upload-img:hover {
    border: 1px dashed #2d8cf0;
  }
</style>
